import React from 'react';
import { Button, Switch, Table, Modal, message, Tooltip } from 'antd';

import Search from 'antd/lib/input/Search';
import { ColumnsType } from 'antd/lib/table';

import { checkPermission } from 'permission/Index';
import { NumPropInfo } from '../../../schema/NumProp';
import {
  getNumPropList,
  deleteNumProp,
  enableNumProp,
  enableSenstive,
} from '../../../servers/servers';
import { clearNull, deleteRowChangePageNum, getTableIndex } from '../../../../utils/tools';
import { NumPropPop } from './component/NumPropPop';
import './style.scss';
import { QuestionCircleFilled } from '@ant-design/icons';

/**
 * 号码属性管理props
 */
interface IProps {}
/**
 * 号码属性管理state
 */
export interface IState {
  // 号码属性名称
  attributeName: string;
  // 新增号码属性抽屉控件显隐
  operationVisible: boolean;
  // 展示在table的数据
  tableData: NumPropInfo[];
  // 详情对话框是否显示
  detailVisible: boolean;
  // 当前选中所要查看详情的数据
  current?: NumPropInfo;
  // 分页相关数据
  pageInfo: {
    pageTotal: number;
    pageNum: number;
    pageSize: number;
  };
  tableLoading: boolean;
}

/**
 * 号码属性管理页
 */
class NumProp extends React.Component<IProps, IState> {
  /**
   * table列头
   * 因为table列头相对固定，不需要响应式地修改视图，所以记录在类的私有属性中而不是react state中，轻量的state利于提升性能
   */
  private columns: ColumnsType<NumPropInfo>;

  //子组件 号码属性操作 的引用
  private operationRef: React.RefObject<NumPropPop> | undefined;

  constructor(props: IProps) {
    super(props);
    // 初始数据
    this.state = {
      attributeName: '',
      detailVisible: false,
      operationVisible: false,
      current: undefined,
      tableData: [],
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableLoading: false,
    };

    const statusTitle = (
      <div>
        数据脱敏&nbsp;
        <Tooltip
          overlayStyle={{ maxWidth: 500 }}
          placement="right"
          arrowPointAtCenter
          title={
            <div style={{ fontSize: 12 }}>开关开启后，属性在界面展示和数据导出时会隐藏部分</div>
          }
        >
          <QuestionCircleFilled style={{ fontSize: 16 }} />
        </Tooltip>
      </div>
    );

    this.columns = [
      {
        title: '序号',
        width: 80,
        dataIndex: 'index',
        key: 'index',
        render: (text, record, index) =>
          getTableIndex(index, this.state.pageInfo.pageSize, this.state.pageInfo.pageNum),
      },
      {
        title: '属性名称',
        dataIndex: 'attributeName',
        key: 'attributeName',
      },
      {
        title: '助记符',
        dataIndex: 'attributeMnemonic',
        key: 'attributeMnemonic',
      },
      {
        title: '描述',
        dataIndex: 'attributeDesc',
        key: 'attributeDesc',
      },
      {
        title: '类别',
        dataIndex: 'attributeType',
        key: 'attributeType',
        render: (text, record, index) => {
          if (text === '1') {
            return '自定义属性';
          } else {
            return '系统属性';
          }
        },
      },
      {
        title: '状态',
        dataIndex: 'attributeSwitch',
        key: 'attributeSwitch',
        render: (text, record, index) => {
          return (
            <>
              <Switch
                disabled={
                  checkPermission('/client/numAttr/enable')
                    ? record.attributeType === '1'
                      ? false
                      : true
                    : true
                }
                checked={record.attributeSwitch === '0' ? true : false}
                onChange={enable => {
                  this.setNumPropEnable(enable, record);
                }}
              />
            </>
          );
        },
      },
      {
        title: statusTitle,
        dataIndex: 'sensitiveSwitch',
        key: 'sensitiveSwitch',
        render: (text, record, index) => {
          return (
            <>
              <Switch
                disabled={record.attributeType === '1' ? false : true}
                checked={record.sensitiveSwitch === 0 ? true : false}
                onChange={enable => {
                  this.changeSenstive(enable, record);
                }}
              />
            </>
          );
        },
      },
      {
        title: '创建时间',
        dataIndex: 'attributeCreateTime',
        key: 'attributeCreateTime',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        key: 'operation',
        render: (text, record, index) => {
          return this.renderOperation(text, record, index);
        },
      },
    ];
    this.operationRef = React.createRef();
  }

  public componentDidMount() {
    this.fetchList();
  }

  /**
   * 停用/启用 号码属性
   */
  private setNumPropEnable(enable: boolean, record: NumPropInfo): void {
    if (!enable) {
      Modal.confirm({
        content: '停用后将无法继续使用，确定停用吗',
        onOk: () => {
          enableNumProp(record.attributeId as number, {
            attributeSwitch: '1',
          })
            .then(res => {
              if (res.code === 0) {
                message.success('停用成功');
                this.fetchList();
              }
            })
            .catch(error => {
              console.error(`系统异常: ${JSON.stringify(error)}`);
            });
        },
      });
    } else {
      enableNumProp(record.attributeId as number, {
        attributeSwitch: '0',
      })
        .then(res => {
          if (res.code === 0) {
            message.success('启用成功');
            this.fetchList();
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    }
  }

  /**
   * 停用/启用 敏感信息开关
   */
  private changeSenstive(enable: boolean, record: NumPropInfo): void {
    if (!enable) {
      enableSenstive(record.attributeId as number, {
        sensitiveSwitch: 1,
      })
        .then(res => {
          if (res.code === 0) {
            message.success('关闭成功');
            this.fetchList();
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    } else {
      enableSenstive(record.attributeId as number, {
        sensitiveSwitch: 0,
      })
        .then(res => {
          if (res.code === 0) {
            message.success('开启成功');
            this.fetchList();
          }
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    }
  }

  /**
   * 渲染操作按钮
   */
  private renderOperation(text: any, record: NumPropInfo, index: number): JSX.Element {
    return (
      <>
        {checkPermission('/client/numAttr/modify') && record.attributeType === '1' && (
          <Button
            type="link"
            onClick={() => {
              this.modify(record);
            }}
          >
            编辑
          </Button>
        )}
        {checkPermission('/client/numAttr/delete') && record.attributeType === '1' && (
          <Button
            type="link"
            onClick={() => {
              this.deleteRecord(record);
            }}
          >
            删除
          </Button>
        )}
      </>
    );
  }

  /**
   * 根据号码属性名称查询列表
   */
  private searchNumProp(name: string) {
    this.setState(
      {
        attributeName: name.trim(),
      },
      () => {
        this.jumpPage(1);
      }
    );
  }

  /**
   * 编辑号码属性交互
   */
  private modify(record: NumPropInfo) {
    const modal = this.operationRef?.current;
    modal && modal.open('modify');
    modal && modal.setValue(record);
  }
  /**
   * 删除数据后更新
   */
  private deleteFresh(size: number) {
    const { pageTotal, pageNum, pageSize } = this.state.pageInfo;
    const newPageNum = deleteRowChangePageNum(size, pageTotal, pageNum, pageSize);
    this.setState(
      {
        pageInfo: {
          pageTotal,
          pageSize,
          pageNum: newPageNum,
        },
      },
      () => {
        this.fetchList();
      }
    );
  }
  /**
   * 删除号码属性交互
   */
  private deleteRecord(record: NumPropInfo) {
    Modal.confirm({
      content: '删除属性后无法恢复，确定删除吗',
      onOk: () => {
        deleteNumProp(record.attributeId)
          .then(res => {
            if (res.code === 0) {
              message.success('删除成功');
              this.deleteFresh(1);
            }
          })
          .catch(error => {
            console.error(`系统异常: ${JSON.stringify(error)}`);
          });
      },
    });
  }

  /**
   * 获取列表数据
   */
  private fetchList() {
    this.setState({
      tableLoading: true,
    });
    const { attributeName, pageInfo } = this.state;
    getNumPropList(
      clearNull({
        attributeName: attributeName,
        pageNo: pageInfo.pageNum,
        pageSize: pageInfo.pageSize,
      })
    )
      .then(res => {
        this.setState({
          tableLoading: false,
        });
        pageInfo.pageTotal = res.count as number;
        this.setState({
          tableData: res.data,
          pageInfo: pageInfo,
        });
      })
      .catch(error => {
        this.setState({
          tableLoading: false,
        });
        console.error(`系统异常: ${JSON.stringify(error)}`);
      });
  }

  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }
  render() {
    const {
      tableData,
      tableLoading,
      pageInfo: { pageNum, pageSize, pageTotal },
    } = this.state;

    return (
      <>
        <div className="mgr-header">
          <div className="mgr-header-left">
            <Search
              className="mgr-header-search"
              placeholder="请输入属性名称"
              enterButton="搜索"
              onSearch={value => this.searchNumProp(value)}
            />
          </div>
          <div className="mgr-header-right">
            {checkPermission('/client/numAttr/add') && (
              <Button
                type="primary"
                onClick={() => {
                  this.operationRef?.current?.open('create');
                }}
              >
                新建属性
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <Table
            loading={tableLoading}
            scroll={{ x: 'max-content' }}
            columns={this.columns}
            dataSource={tableData}
            rowKey={record => record.attributeId as number}
            pagination={{
              showSizeChanger: true,
              total: pageTotal,
              showTotal: total => `共 ${total} 条`,
              current: pageNum,
              pageSize: pageSize,
              onChange: (pageNum, pageSize) => {
                this.jumpPage(pageNum, pageSize as number);
              },
            }}
          />
        </div>
        <NumPropPop
          ref={this.operationRef}
          callback={id => {
            id ? this.fetchList() : this.jumpPage(1);
          }}
        />
      </>
    );
  }
}

export default NumProp;
